package com.core.reach.oauth2server.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.annotation.Resource;

/**
 * @author Mr_zhangmu
 * @version V1.0
 * @description: TODO
 * @date 2020/6/19 15:31
 **/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {

    /**
     * TUserService 实现 UserDetailsService 接口，获取用户信息
     */
    @Resource(name = "tUserService")
    private UserDetailsService userService;

    @Resource
    private TokenStore tokenStore;

    /**
     * 查询自定义数据表加载客户端信息
     */
    @Resource(name = "myClientDetailsService")
    private ClientDetailsService clientDetailsService;

    /**
     * 注入authenticationManager
     * 来支持 password grant type
     */
    @Resource
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        //开放oauth2的授权端点
        //允许表单认证
        security.allowFormAuthenticationForClients()
                .tokenKeyAccess("permitAll()")
                //允许check_token访问
                .checkTokenAccess("isAuthenticated()")
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        //使用redis
        endpoints.tokenStore(tokenStore)
                //刷新token时，同时刷新refreshToken
                .reuseRefreshTokens(Boolean.FALSE)
                .userDetailsService(userService)
                //来支持 password grant type
                .authenticationManager(authenticationManager)
                // 不加报错"method_not_allowed"
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients)
            throws Exception {
        //使用自定义的ClientDetailsService
        clients.withClientDetails(clientDetailsService);
    }

}

